//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<RegularGameMessage.cpp>
///	@path	~/src/appear/xwin/
///	@date	2007/11/06
///	@desc	Regular game message filter.

#include "config/config.h"

#include "appear/xwin/RegularGameMessage.h"

#include "engine/xcore/xeres_engine.h"
#include "engine/xcore/event_center.h"

namespace xeres {

	// ctor
	RegularGameMessage::RegularGameMessage( void )
	{
	}

	// dtor
	RegularGameMessage::~RegularGameMessage( void )
	{
	}

	static inline void _get_rect( HWND hWnd , WindowEventInfo& info )
	{
		RECT rect;
		::GetClientRect( hWnd , &rect );
		info.m_rect.set( rect.left , rect.top , rect.right , rect.bottom );
	}

	// filter
	bool RegularGameMessage::Filter( HWND hWnd , UINT message , WPARAM wParam , LPARAM lParam )
	{
		switch( message )
		{
		case WM_ACTIVATEAPP:
			if( m_activate.IsValid() )
			{
				WindowEventInfo info;
				_get_rect( hWnd , info );
				info.m_tag = (LOWORD(wParam) == WA_INACTIVE) ? WINDOW_EVENT_INACTIVATE : WINDOW_EVENT_ACTIVATE;
				m_activate->Active( &info );
			}
			return true;

		case WM_ENTERSIZEMOVE:
			if( m_size.IsValid() )
			{
				WindowEventInfo info;
				_get_rect( hWnd , info );
				info.m_tag = WINDOW_EVENT_ENTERSIZING;
				m_size->Active( &info );
			}
			return true;

		case WM_EXITSIZEMOVE:
			if( m_size.IsValid() )
			{
				WindowEventInfo info;
				_get_rect( hWnd , info );
				info.m_tag = WINDOW_EVENT_EXITSIZING;
				m_size->Active( &info );
			}
			return true;

		case WM_SIZE:
			if( m_size.IsValid() )
			{
				WindowEventInfo info;
				_get_rect( hWnd , info );
				info.m_tag = ( wParam == SIZE_MINIMIZED ) ? WINDOW_EVENT_MINIMIZED : WINDOW_EVENT_NONE;;
				m_size->Active( &info );
			}
			return true;

		case WM_PAINT:
			if( m_paint.IsValid() )
			{
				WindowEventInfo info;
				_get_rect( hWnd , info );
				info.m_tag = WINDOW_EVENT_NONE;
				m_paint->Active( &info );
			}
			return true;

		case WM_ERASEBKGND: // omit eraser background
			return true;
		}
		return false;
	}

	// register window callback
	bool RegularGameMessage::ConnectEngine( Engine& engine )
	{
		if( m_activate.IsValid() || m_size.IsValid() || m_paint.IsValid() )
			return false;

		m_activate = new CWindowEvent;
		m_size = new CWindowEvent;
		m_paint = new CWindowEvent;

		engine.RegisterEvent( _S("message/activate") , m_activate , true );
		engine.RegisterEvent( _S("message/size") , m_size , true );
		engine.RegisterEvent( _S("message/paint") , m_paint , true );

		return true;
	}

} // namespace xeres
